Ext.define('Seq.tree.NaviTreeController', {
    extend: 'Ext.app.ViewController',

    onNaviTreeSelect: function (tree, record, index, eOpts) {
        let me = this, ct = me.getReferences().contentContainer;

        let vm = Ext.getApplication().getMainView().getViewModel();
        vm.set("global_tree_record", record);

        ct.getViewModel().set('record', record);
        ct && ct.fireEvent('refreshdata', ct, record, null, {});
    },

    onRefreshData: function (view, record, params, opts) {
        let me = this, tree = me.getReferences().navitree, store = tree.getStore();
        if (opts && opts.click) {
            let selected = tree.getSelection();
            if (0 < selected.length) {
                store.load({
                    node: selected[0]
                });
                me.onNaviTreeSelect(tree, selected[0]);
            } else {
                store.load();
            }
        } else {
            let global = Ext.getApplication().getMainView().getViewModel().getData().global_tree_record;
            if (global) {
                me.onGlobalExpand(tree, global);
            } else if (tree.getSelection().length == 0) { // 重新选中
                tree.fireEvent('viewready', tree);
            }
        }
    },

    onGlobalExpand(tree, record) {
        let ids = [], lasted = record.data.id;
        while (record.parentNode) {
            ids.push(record.data.id);
            record = record.parentNode;
        }
        this.expandNode(tree, tree.getRootNode(), ids, lasted);
    },

    expandNode(tree, node, ids, lasted) {
        let me = this;
        if (node.data.id == lasted) { // 直到选中的节点
            tree.setSelection(node);
        } else if (ids.length > 0) {
            let id = ids.pop();
            tree.expandNode(node, false, function () {
                let next = node.findChildBy(function (child) {
                    return child.data.id == id;
                });
                if (next) {
                    if (ids.length > 0) {
                        me.expandNode(tree, next, ids, lasted);
                    } else {
                        tree.getSelectionModel().select(next);
                    }
                } else if (node.parentNode != null) {
                    tree.getSelectionModel().select(node);
                }
            }, me);
        }
    }
});